package org.ctstudio.common.utils;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class SqlTimeEditor extends PropertyEditorSupport {
  private static final DateFormat DEFAULT_FORMAT = new SimpleDateFormat("HH:mm");

  private DateFormat dateFormat;

  public SqlTimeEditor(DateFormat dateFormat) {
    this.dateFormat = dateFormat == null ? DEFAULT_FORMAT : dateFormat;
  }

  public SqlTimeEditor() {
    this(null);
  }

  @SuppressWarnings("deprecation")
  public void setAsText(String text) throws IllegalArgumentException {
    if (text == null || text.length() == 0) {
      setValue(null);
    } else {
      String[] hms = text.split(":");
      int h = hms.length > 0 ? Integer.parseInt(hms[0]) : 0;
      int m = hms.length > 1 ? Integer.parseInt(hms[1]) : 0;
      int s = hms.length > 2 ? Integer.parseInt(hms[2]) : 0;
      setValue(new java.sql.Time(h, m, s));
    }
  }

  public String getAsText() {
    java.sql.Time value = (java.sql.Time) getValue();
    return value != null ? this.dateFormat.format(value) : "";
  }
}